using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using CCWin.SkinControl;

namespace ERPWinFormWork.Material
{
    public partial class PeopleSelectForm : Skin_Mac
    {
        private ApiClient _apiClient;
        private DataTable _peopleData;
        private string _selectedPeopleName;
        private string _selectedPeopleId;

        public string SelectedPeopleName => _selectedPeopleName;
        public string SelectedPeopleId => _selectedPeopleId;

        public PeopleSelectForm()
        {
            InitializeComponent();
            _apiClient = new ApiClient("http://localhost:5280/api/");
            InitializeDataGridView();
            LoadPeopleData();
        }

        private void InitializeDataGridView()
        {
            // 设置DataGridView的基本属性
            dgvPeople.AllowUserToAddRows = false;
            dgvPeople.AllowUserToDeleteRows = false;
            dgvPeople.ReadOnly = false;
            dgvPeople.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvPeople.MultiSelect = false;
            dgvPeople.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            // 添加复选框列
            var checkBoxColumn = new DataGridViewCheckBoxColumn
            {
                Name = "colSelect",
                HeaderText = "选择",
                Width = 60,
                ReadOnly = false
            };
            dgvPeople.Columns.Add(checkBoxColumn);

            // 添加其他列
            dgvPeople.Columns.Add("colPeopleId", "人员编号");
            dgvPeople.Columns.Add("colPeopleName", "人员姓名");
            dgvPeople.Columns.Add("colDepartment", "所属部门");
            dgvPeople.Columns.Add("colPosition", "职位");
            dgvPeople.Columns.Add("colPhone", "联系电话");

            // 绑定单元格点击事件
            dgvPeople.CellClick += DgvPeople_CellClick;
        }

        private void DgvPeople_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0) // 复选框列
            {
                // 清除其他行的选择
                for (int i = 0; i < dgvPeople.Rows.Count; i++)
                {
                    if (i != e.RowIndex)
                    {
                        dgvPeople.Rows[i].Cells[0].Value = false;
                    }
                }

                // 设置当前行选中
                dgvPeople.Rows[e.RowIndex].Cells[0].Value = true;

                // 获取选中的人员信息
                if (e.RowIndex < _peopleData.Rows.Count)
                {
                    var row = _peopleData.Rows[e.RowIndex];
                    _selectedPeopleName = row["PeopleName"]?.ToString() ?? "";
                    _selectedPeopleId = row["PeopleId"]?.ToString() ?? "";
                }
            }
        }

        private async void LoadPeopleData()
        {
            try
            {
                // 这里应该调用实际的API获取人员数据
                // 暂时使用模拟数据
                _peopleData = CreateMockData();
                BindDataToGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载人员数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private DataTable CreateMockData()
        {
            var dt = new DataTable();
            dt.Columns.Add("PeopleId", typeof(string));
            dt.Columns.Add("PeopleName", typeof(string));
            dt.Columns.Add("Department", typeof(string));
            dt.Columns.Add("Position", typeof(string));
            dt.Columns.Add("Phone", typeof(string));

            // 添加模拟数据
            dt.Rows.Add("P001", "张三", "生产部", "操作员", "13800138001");
            dt.Rows.Add("P002", "李四", "生产部", "组长", "13800138002");
            dt.Rows.Add("P003", "王五", "质检部", "质检员", "13800138003");
            dt.Rows.Add("P004", "赵六", "仓库部", "仓管员", "13800138004");
            dt.Rows.Add("P005", "钱七", "生产部", "操作员", "13800138005");

            return dt;
        }

        private void BindDataToGrid()
        {
            dgvPeople.Rows.Clear();
            foreach (DataRow row in _peopleData.Rows)
            {
                int rowIndex = dgvPeople.Rows.Add();
                dgvPeople.Rows[rowIndex].Cells[1].Value = row["PeopleId"];
                dgvPeople.Rows[rowIndex].Cells[2].Value = row["PeopleName"];
                dgvPeople.Rows[rowIndex].Cells[3].Value = row["Department"];
                dgvPeople.Rows[rowIndex].Cells[4].Value = row["Position"];
                dgvPeople.Rows[rowIndex].Cells[5].Value = row["Phone"];
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            // 实现搜索功能
            string searchText = txtSearch.Text.Trim();
            if (!string.IsNullOrEmpty(searchText))
            {
                var filteredRows = _peopleData.AsEnumerable()
                    .Where(row => row.Field<string>("PeopleId").Contains(searchText) ||
                                 row.Field<string>("PeopleName").Contains(searchText) ||
                                 row.Field<string>("Department").Contains(searchText))
                    .ToArray();

                var filteredTable = _peopleData.Clone();
                foreach (var row in filteredRows)
                {
                    filteredTable.ImportRow(row);
                }

                _peopleData = filteredTable;
                BindDataToGrid();
            }
            else
            {
                LoadPeopleData();
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_selectedPeopleName))
            {
                MessageBox.Show("请选择一个人", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13) // Enter键
            {
                btnSearch_Click(sender, e);
            }
        }
    }
}
